<template>
  <div>
    <el-row class="lock-btn">
      <el-button-group style="width:1000px">
        <el-button :disabled="userState" size="medium" type="success" @click="addBtn" round>添加</el-button>

        <el-input v-model="queryParams.name" style="width:300px;float: left;margin-left: 1%;" clearable placeholder="请输入区域名称">
      </el-input>

      <el-button :disabled="userState" style="margin-left: 0.6%;margin-top: 0.2%;" size="medium" type="primary" @click="loadAreaList" round>搜索</el-button>

      </el-button-group>
    </el-row>
    <el-row style="box-shadow: rgb(205 205 205) 1px 1px 8px;">
      <el-col :span="24">
        <el-table :header-cell-style="{ background: '#ecf3fd',color:'#000000' }" highlight-current-row ref="areaTable" v-loading="loading" :data="areas" :stripe="true" :row-key="'id'" :max-height="clientHeight" :height="clientHeight" @selection-change="handleTableChange">
          <el-table-column prop="unicode" label="区域编号" width="160" align="center" sortable></el-table-column>
          <el-table-column prop="name" label="区域名称" width="220" align="center"  sortable></el-table-column>
          <el-table-column prop="address" label="区域地址" width="280" align="center" ></el-table-column>
          <el-table-column prop="concentratorUnicode" width="120" align="center" label="集中器ID"></el-table-column>
          <el-table-column prop="parkfieldName" label="所属停车场" width="220" align="center" ></el-table-column>
          <el-table-column prop="operation" label="运维人员" v-if="roleIndex == false" width="280" align="center">
            <template slot-scope="scope">
              <el-tag
                style="margin-left: 0px;"
                :key="tag.id"
                v-for="tag in scope.row.operation"
                closable
                :disable-transitions="false"
                @close="handleClose(tag, scope.row.id)">
                {{tag.name}}
              </el-tag>
              <el-button class="button-new-tag" size="small" @click="showSelect(scope.row.id)">+</el-button>
            </template>

          </el-table-column>
          <el-table-column prop="createDate" label="创建时间"  width="160" align="center"></el-table-column>
          <el-table-column prop="remark" label="备注" width="120" align="center"></el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button :disabled="userState" class="operateBtn" size="mini" type="primary" @click="editBtn(scope.$index, scope.row)" title="编辑">
                <i class="el-icon-edit-outline"></i>
              </el-button>
              <el-button :disabled="userState" class="operateBtn" size="mini" type="danger" @click="delArea(scope.$index, scope.row)" title="删除">
                <i class="el-icon-delete"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" class="page-tool">
        <el-pagination layout="total,sizes,prev, pager,next,jumper" :page-size="pageSize" :total="total" :page-sizes="[10, 20, 30, 40, 100]" @size-change="handlePageChange" @current-change="handleNoChange"></el-pagination>
      </el-col>
    </el-row>
    <el-dialog :title="dialogTitle" :visible.sync="addDialog" :width="'422px'">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="区域编号" :label-width="labelWidth" prop="unicode">
          <el-input v-model="form.unicode" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="区域名称" :label-width="labelWidth" prop="name">
          <el-input v-model="form.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="区域地址" :label-width="labelWidth" prop="address">
          <el-input v-model="form.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="集中器ID" :label-width="labelWidth" prop="concentratorUnicode">
          <el-input v-model="form.concentratorUnicode" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属停车场" :label-width="labelWidth" prop="position">
          <el-select v-model="form.position" placeholder="请选择所属停车场">
            <el-option v-for="parkfield in parkfields" v-bind:key="parkfield.id" :label="parkfield.name" :value="parkfield.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" :label-width="labelWidth">
          <el-input v-model="form.remark" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveArea">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogTitle" :visible.sync="operationDialog" :width="'922px'" @close="canelOperation">
      <el-row>
        <el-col :span="24">
          <el-table ref="operationTable" v-loading="loading" :data="lcqas" :stripe="true" :row-key="'id'" :max-height="operationHeight" :height="operationHeight" @selection-change="handleTableChangeOperation">
            <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="phone" label="联系方式"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="openid" label="openid"></el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" class="page-tool">
          <el-pagination layout="total,sizes,prev, pager,next,jumper" :page-size="pageSizeSelect" :total="totalSelect" :page-sizes="[10, 20, 30, 40, 100]" @size-change="handlePageChangeSelect" @current-change="handleNoChangeSelect"></el-pagination>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="canelOperation">取 消</el-button>
        <el-button type="primary" @click="saveOperation">确 认</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import {
  loadParkfieldApi,
} from "../../api/parkfield.js";
import {
  loadAreaApi,
  loadAreaListApi,
  updateAreaApi,
  addAreaApi,
  delAreaApi,
  addQaforLcAreaApi,
  delQaforLcAreaApi
} from "../../api/area.js";
import {
  loadLcqaApi
} from "../../api/lcqa.js";
import { getNickName, getTestUserName, getRoleId } from "../../util/auth";

export default {
  name: "runInfo",
  data: function () {
    return {
      clientHeight:
        Math.max(
          document.documentElement.scrollHeight,
          document.body.scrollHeight
        ) -
        132 -
        5 +
        10 -
        28,
      labelWidth: "100px",
      loading: false,
      dialogTitle: "",
      pageNo: 1,
      pageSize: 20,
      total: 0,
      multipleSelection: [],
      areas: [],
      parkfields: [],
      form: {},
      addDialog: false,
      managers: [],
      roleIndex: true,

      queryParams: {
      name: "",
      },
  
      selectId:'',
      operationDialog: false,
      operationHeight: '400px',
      pageNoSelect: 1,
      pageSizeSelect: 20,
      totalSelect: 0,
      multipleSelectionOperation: [],
      lcqas:[],
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',

      rules: {
        unicode: [
            { required: true, message: '请输入区域编号', trigger: 'blur' }
          ],
        name: [
            { required: true, message: '请输入区域名称', trigger: 'blur' }
          ],
        address: [
            { required: true, message: '请输入区域地址', trigger: 'blur' }
          ],
        concentratorUnicode: [
            { required: true, message: '请输入集中器ID', trigger: 'blur' }
          ],
        position: [
            { required: true, message: '请选择所属停车场', trigger: 'change' }
          ],
      },

    };
  },
  methods: {
    delArea (index, row) {
      let _this = this;
      this.$confirm('确认删除区域“' + row.name + '”', '提示', {
        type: 'warning'
      })
        .then(_ => {
          delAreaApi(row).then(resp => {
            if (resp.errmsg === "ok") {
              _this.loadAreas(_this.pageNo, _this.pageSize);
              _this.$notify({
                title: "成功",
                message: "区域删除成功",
                type: "success"
              });
            } else {
              _this.$notify({
                title: "失败",
                message: "区域删除失败",
                type: "error"
              });
            }
          });
        })
    },
    saveArea () {
      let _this = this;
      _this.$refs.form.validate((valid) => {
          if (valid) {
            if (_this.dialogTitle === "添加区域") {
              addAreaApi(_this.form).then(resp => {
                _this.addDialog = false;
                if (resp.errmsg === "ok") {
                  _this.loadAreas(_this.pageNo, _this.pageSize);
                  _this.$notify({
                    title: "成功",
                    message: "区域添加成功",
                    type: "success"
                  });
                } else {
                  _this.$notify({
                    title: "失败",
                    message: "区域添加失败",
                    type: "error"
                  });
                }
              });
            } else {
              console.log(_this.form)
              updateAreaApi(_this.form).then(resp => {
                _this.addDialog = false;
                if (resp.errmsg === "ok") {
                  _this.loadAreas(_this.pageNo, _this.pageSize);
                  _this.$notify({
                    title: "成功",
                    message: "区域修改成功",
                    type: "success"
                  });
                } else {
                  _this.$notify({
                    title: "失败",
                    message: "区域修改失败",
                    type: "error"
                  });
                }
              });
            }
          }
        });
    },
    addBtn () {
      let _this = this;
      _this.$nextTick(()=>{
        if(_this.$refs.form != undefined){
          _this.$refs.form.resetFields();
        }
      })
      _this.dialogTitle = "添加区域";
      _this.form = {
        concentratorUnicode: "12345678"
      };
      _this.loadParkfields();
      _this.addDialog = true;
    },
    editBtn (index, row) {
      let _this = this;
      _this.$nextTick(()=>{
        if(_this.$refs.form != undefined){
          _this.$refs.form.resetFields();
        }
      })
      _this.dialogTitle = "修改区域";
      // console.log(row)
      _this.form = row;
      _this.loadParkfields();
      _this.addDialog = true;
    },
    handlePageChange (pageSize) {
      this.pageSize = pageSize;
      this.loadAreas(this.pageNo, this.pageSize);
    },
    handleNoChange (pageNo) {
      this.pageNo = pageNo;
      this.loadAreas(this.pageNo, this.pageSize);
    },
    handleTableChange (val) {
      this.multipleSelection = val;
    },
    loadParkfields (pageNo, pageSize) {
      let _this = this;
      loadParkfieldApi(pageNo, pageSize).then(resp => {
        _this.parkfields = resp.data.dataList;
      });
    },



    loadAreaList () {
      let _this = this;
      _this.loading = true;
      loadAreaListApi({ name:_this.queryParams.name }).then(resp => {
        _this.areas = resp.data.dataList;
        
        for(var j=0;j<_this.areas.length;j++){
          for(var i=0;i<_this.areas[j].lcQas.length;i++){
            _this.dynamicTags.push({name:_this.areas[j].lcQas[i].name,id:_this.areas[j].lcQas[i].id})
          }
          _this.areas[j].operation = _this.dynamicTags
          _this.dynamicTags = []
        }
        _this.total = resp.data.totalNum;
        _this.loading = false;
        
      });
      _this.loading = false;
    },

    loadAreas (pageNo, pageSize) {
      let _this = this;
      _this.loading = true;
      loadAreaApi({ pageNo: pageNo, pageSize: pageSize,name:_this.queryParams.name }).then(resp => {
        _this.areas = resp.data.dataList;
        // console.log(_this.areas)
        for(var j=0;j<_this.areas.length;j++){
          for(var i=0;i<_this.areas[j].lcQas.length;i++){
            _this.dynamicTags.push({name:_this.areas[j].lcQas[i].name,id:_this.areas[j].lcQas[i].id})
          }
          _this.areas[j].operation = _this.dynamicTags
          _this.dynamicTags = []
        }
        _this.total = resp.data.totalNum;
        _this.loading = false;
      });
    },


    queryBtn () {
      let _this = this
      _this.loading = true
     
      _this.loadAreas(_this.pageNo, _this.pageSize, _this.queryParams)
      
    },


    //运维人员
    loadLcqa(pageNoSelect, pageSizeSelect, areaId) {
      let _this = this;
      loadLcqaApi(pageNoSelect, pageSizeSelect, areaId).then(resp => {
        _this.totalSelect = resp.data.totalNum;
        _this.lcqas = resp.data.dataList;
        for(var i=0;i<_this.lcqas.length;i++) {
          _this.lcqas[i].selectAreaId = areaId
        }
      });
    },

    handlePageChangeSelect (pageSizeSelect) {
      this.pageSizeSelect = pageSizeSelect;
      this.loadLcqa(this.pageNoSelect, this.pageSizeSelect,this.selectId);
    },
    handleNoChangeSelect (pageNoSelect) {
      this.pageNoSelect = pageNoSelect;
      this.loadLcqa(this.pageNoSelect, this.pageSizeSelect,this.selectId);
    },

    handleClose(tag,id) {
      // console.log(tag)
      // console.log(tag.id,id)
      let _this = this;
      _this.$confirm('确认删除“' + tag.name + '”', '提示', {
        type: 'warning'
      })
        .then(_ => {
          delQaforLcAreaApi(tag.id, id).then(resp => {
            if (resp.errmsg === "ok") {
              _this.loadAreas(_this.pageNo, _this.pageSize);
              _this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success"
              });
            } else {
              _this.$notify({
                title: "失败",
                message: "删除失败",
                type: "error"
              });
            }
          });
        })
        .catch((e) => {})
    },

    showSelect(id) {
      let _this = this;
      _this.selectId = id;
      console.log(_this.pageNoSelect+";"+ _this.pageSizeSelect+";"+id);
      _this.loadLcqa(_this.pageNoSelect, _this.pageSizeSelect, id)      
      _this.operationDialog = true
      
    },

    handleTableChangeOperation (val) {
      this.multipleSelectionOperation = val;
    },

    saveOperation() {
      let _this = this;
      console.log(_this.multipleSelectionOperation);
      if(_this.multipleSelectionOperation.length == 0){
        _this.$notify({
          title: "提示",
          message: "请选择一名运维人员进行添加",
          type: "warning"
        });
        return
      }
      let ids = new Array();
      for (let i = 0; i < _this.multipleSelectionOperation.length; i++) {
        ids[i] = _this.multipleSelectionOperation[i].id
      }
      var selectAreaId = _this.multipleSelectionOperation[0].selectAreaId
      addQaforLcAreaApi(ids, selectAreaId).then(resp => {
        // _this.loadAreas(_this.pageNo, _this.pageSize);
        _this.loadAreaList();
        _this.operationDialog = false
      });
    },

    canelOperation() {
      let _this = this;
      _this.multipleSelectionOperation = []
      _this.$refs.operationTable.clearSelection();
      _this.operationDialog = false
    },

  },
  computed: {
    userState () {
      return getNickName() === getTestUserName();
    }
  },
  mounted: function () {
    this.$nextTick(function () {
      this.loadAreas(this.pageNo, this.pageSize);
      this.roleIndex = getRoleId()==1?false:true;
      console.log(this.roleIndex)
    });
  }
};
</script>

<style scoped>


.page-tool div {
  text-align: right;
}

.lock-btn {
  margin-bottom: 5px;
  margin-top: -10px;
}

.operateBtn {
  font-size: 18px;
  width: 32px;
  height: 32px;
  padding: 0;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

</style>